package org.example.friend.service.user.impl;



import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import org.example.api.domain.RemoteJudgeService;
import org.example.api.domain.UserExeResult;
import org.example.api.domain.dto.JudgeSubmitDTO;
import org.example.api.domain.vo.UserQuestionResultVO;
import org.example.common.core.constants.Constants;
import org.example.common.core.domain.Result;
import org.example.common.core.enums.ProgramType;
import org.example.common.core.enums.QuestionResType;
import org.example.common.core.enums.ResultCode;
import org.example.common.core.utils.ThreadLocalUtil;
import org.example.common.security.exception.ServiceException;
import org.example.friend.domain.question.Question;
import org.example.friend.domain.question.QuestionCase;
import org.example.friend.domain.question.es.QuestionES;
import org.example.friend.domain.user.UserSubmit;
import org.example.friend.domain.user.dto.UserSubmitDTO;
import org.example.friend.elasticsearch.QuestionRepository;
import org.example.friend.mapper.question.QuestionMapper;
import org.example.friend.mapper.user.UserSubmitMapper;
import org.example.friend.rabbit.JudgeProducer;
import org.example.friend.service.user.UserQuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

@Service
public class UserQuestionServiceImpl implements UserQuestionService {

    @Autowired
    private QuestionRepository questionRepository;

    @Autowired
    private QuestionMapper questionMapper;

    @Autowired
    private RemoteJudgeService remoteJudgeService;

    @Autowired
    private JudgeProducer judgeProducer;

    @Autowired
    private UserSubmitMapper userSubmitMapper;


    @Override
    public Result<UserQuestionResultVO> submit(UserSubmitDTO submitDTO) {
        Integer programType = submitDTO.getProgramType();
        //Java语言逻辑   只在friend包中处理判题所需要的DTO，判题本身的主要逻辑是在Judge包中进行处理
        if (ProgramType.JAVA.getValue().equals(programType)) {
            //只是处理了判题所需要的DTO
            JudgeSubmitDTO judgeSubmitDTO = assembleJudgeSubmitDTO(submitDTO);
            //真正的判题逻辑处理
            return remoteJudgeService.doJudgeJavaCode(judgeSubmitDTO);
        }
        throw new ServiceException(ResultCode.FAILED_NOT_SUPPORT_PROGRAM);
    }

    @Override
    public boolean rabbitSubmit(UserSubmitDTO submitDTO) {
        Integer programType = submitDTO.getProgramType();
        if (ProgramType.JAVA.getValue().equals(programType)) {
            //按照java逻辑处理
            JudgeSubmitDTO judgeSubmitDTO = assembleJudgeSubmitDTO(submitDTO);
            //生产者将消息在UserQuestionController发送给Judge包中的JudgeConsumer进行消息消费
            judgeProducer.produceMsg(judgeSubmitDTO);
            return true;
        }
        throw new ServiceException(ResultCode.FAILED_NOT_SUPPORT_PROGRAM);
    }

    @Override
    public UserQuestionResultVO exeResult(Long examId, Long questionId, String currentTime) {
        //获取结果也需要有用户Id，先通过线程池本地变量获取
        Long userId = ThreadLocalUtil.get(Constants.USER_ID, Long.class);
        //从数据库中查询用户提交的数据
        UserSubmit userSubmit = userSubmitMapper.selectCurrentUserSubmit(userId, examId, questionId, currentTime);
        //判断userSubmit是否存在
        UserQuestionResultVO result = new UserQuestionResultVO();
        if (userSubmit == null) {
            result.setPass(QuestionResType.IN_JUDGE.getValue());
        }else {
            result.setPass(userSubmit.getPass());
            result.setExeMessage(userSubmit.getExeMessage());
            if (CollectionUtil.isNotEmpty(Collections.singleton(userSubmit.getCaseJudgeRes()))) {
                result.setUserExeResultList(JSON.parseArray(userSubmit.getCaseJudgeRes(), UserExeResult.class));
            }
        }
        return result;
    }

    private JudgeSubmitDTO assembleJudgeSubmitDTO(UserSubmitDTO submitDTO) {
        JudgeSubmitDTO judgeSubmitDTO = new JudgeSubmitDTO();
        //先从ES中查询题目的信息
        QuestionES questionES = questionRepository.findById(submitDTO.getQuestionId()).orElse(null);
        if (questionES != null) {
            //直接从其中复制信息
            BeanUtil.copyProperties(questionES, judgeSubmitDTO);
        }else {
            //为空则从 数据库中获取信息，并刷新缓存ES
            Question question = questionMapper.selectById(submitDTO.getQuestionId());
            BeanUtil.copyProperties(question, judgeSubmitDTO);
            //刷新ES操作
            questionES = new QuestionES();
            BeanUtil.copyProperties(question, questionES);
            questionRepository.save(questionES);
        }
        //给JudgeSubmitDTO的其他属性进行赋值操作
        judgeSubmitDTO.setQuestionId(submitDTO.getQuestionId());
        judgeSubmitDTO.setUserId(ThreadLocalUtil.get(Constants.USER_ID,Long.class));
        judgeSubmitDTO.setExamId(submitDTO.getExamId());
        judgeSubmitDTO.setProgramType(submitDTO.getProgramType());
        judgeSubmitDTO.setUserCode(codeConnect(submitDTO.getUserCode(),questionES.getMainFuc()));
        //获取Input和output需要先将前端传过来的JSON字符串进行反序列表  (题目的输入和预期输出参数在QuestionES中有进行保存.再通过QuestionCase的类来进行获取)
        List<QuestionCase> list = JSONUtil.toList(questionES.getQuestionCase(), QuestionCase.class);
        //在通过stream流来获取对应的input和output
        List<String> input = list.stream().map(QuestionCase::getInput).toList();
        List<String> output = list.stream().map(QuestionCase::getOutput).toList();
        judgeSubmitDTO.setInputList(input);
        judgeSubmitDTO.setOutputList(output);
        return judgeSubmitDTO;
    }


    //用户输入的代码和main方法代码进行拼接
    //样式：public class Test {
    //    void hello() { System.out.println("Hello"); }
    //}
    // ↑ 此处是最后一个 '}' 的位置（下一步在此前插入）
    //
    //  插入后：
    //  public class Test {
    //      void hello() { System.out.println("Hello"); }
    //  }       // ① 最后一个 '}' 之前的内容（含换行和缩进）
    //          // ② 换行符 \n
    //          + mainFunc 内容
    //          // ④ 换行符 \n
    //          + }        // ⑤ 最后一个 '}' 及之后的内容（本例中无后续内容）


    //  public class Test {
    //    void hello() { System.out.println("Hello"); }
    //    public static void main(String[] args) { new Test().hello(); }
    //
    //  }
    private String codeConnect(String userCode, String mainFunc) {
        String targetCharacter = "}";
        int targetLastIndex = userCode.lastIndexOf(targetCharacter);
        if (targetLastIndex != -1) {
            return userCode.substring(0, targetLastIndex) + "\n" + mainFunc + "\n" + userCode.substring(targetLastIndex);
        }
        throw new ServiceException(ResultCode.FAILED);
    }
}
